/*
 *    This program is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation; either version 2 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 *    2010 year
 *    Author: Michael Khromov aka MikeDM (Mike D'Morto)
 *    E-Mail: mikedmorto@gmail.com
 */

#include "dbconnector_mysql.h"
#include <QDebug>
#include <QString>

bool Dbconnector_mysql::init(const QString &cfg){
    // первостепенная задача прочитать конфигурацию и убедиться что она верная.
    this->dbcfg = cfg;
    QStringList cfglist = cfg.split(",");
    // поиск dbhost
    this->dbhost="";
    for(int i = 0 ; i < cfglist.size(); i++){
        QStringList a = cfglist.at(i).split("=");
        if(a.at(0) == "host" and a.size() >= 2 ){
            this->dbhost = a.at(1);
        }
    }
    // поиск dbsocket;
    this->dbsocket="";
    for(int i = 0 ; i < cfglist.size(); i++){
        QStringList a = cfglist.at(i).split("=");
        if(a.at(0) == "socket" and a.size() >= 2 ){
            this->dbsocket = a.at(1);
        }
    }
    // поиск порта
    this->dbport=DEF_DBPORT;
    for(int i = 0 ; i < cfglist.size(); i++){
        QStringList a = cfglist.at(i).split("=");
        if(a.at(0) == "port" and a.size() >= 2 ){
            this->dbport = a.at(1).toInt();
        }
    }
    // поиск login
    this->dbusername="";
    for(int i = 0 ; i < cfglist.size(); i++){
        QStringList a = cfglist.at(i).split("=");
        if(a.at(0) == "login" and a.size() >= 2 ){
            this->dbusername = a.at(1);
        }
    }
    // поиск password
    this->dbpassword="";
    for(int i = 0 ; i < cfglist.size(); i++){
        QStringList a = cfglist.at(i).split("=");
        if(a.at(0) == "password" and a.size() >= 2 ){
            this->dbpassword = a.at(1);
        }
    }
    // поиск database name
    this->dbname="";
    for(int i = 0 ; i < cfglist.size(); i++){
        QStringList a = cfglist.at(i).split("=");
        if(a.at(0) == "base" and a.size() >= 2 ){
            this->dbname = a.at(1);
        }
    }
    // совершаем пробное подключение к базе данных с целью проверки ее наличия.
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL","test");
    // конфигурируем.
    if(!this->dbsocket.isEmpty()){
        db.setConnectOptions(QString("UNIX_SOCKET=%1").arg(this->dbsocket));
    }else{
        db.setHostName(this->dbhost);
        db.setPort(this->dbport);
    }
    db.setDatabaseName(this->dbname);
    db.setUserName(this->dbusername);
    db.setPassword(this->dbpassword);
    if(!db.open()){
        // ошибка соединения с бд
        return false;
    }else{
        db.close();
        //db.removeDatabase("test");
        return true;
    }
}

bool Dbconnector_mysql::newWorker(const QString &sessionID){
    // создаем нового рабочего, заносим его в карту, соединяем слотами, и стартуем поток.
    this->sigPutLog(PLUGIN_NAME,2,QString("start new worker %1").arg(sessionID));
    Worker * wrk = new Worker(this->dbcfg, sessionID, this);
    connect(wrk,SIGNAL(sigPutLog(QString,int,QString)),this,SLOT(slotPutLog(QString,int,QString)));
    connect(wrk,SIGNAL(sigFinish(QString,QStringList)),this,SLOT(slotWrkFinish(QString,QStringList)));
    connect(wrk,SIGNAL(sigError(QString,QString)),this,SLOT(slotWrkError(QString,QString)));
    map.insert(sessionID,wrk);
    return true;
}

bool Dbconnector_mysql::closeWorker(const QString &sessionID){
    this->sigPutLog(PLUGIN_NAME,2,QString("stop new worker").arg(sessionID));
    Worker * wrk =  map.value(sessionID);
    disconnect(wrk,SIGNAL(sigPutLog(QString,int,QString)),this,SLOT(slotPutLog(QString,int,QString)));
    disconnect(wrk,SIGNAL(sigFinish(QString,QStringList)),this,SLOT(slotWrkFinish(QString,QStringList)));
    disconnect(wrk,SIGNAL(sigError(QString,QString)),this,SLOT(slotWrkError(QString,QString)));
    map.remove(sessionID);
    return true;
}

void Dbconnector_mysql::slotTransactionStart(const QString &sessionID){

}

void Dbconnector_mysql::slotTransactionCommit(const QString &sessionID){

}

void Dbconnector_mysql::slotTransactionRollback(const QString &sessionID){

}

void Dbconnector_mysql::slotQuery(const QString &sessionID, const QString & metafunction, QStringList params){

}

void Dbconnector_mysql::slotPutLog(const QString &owner, int level, const QString &text){
    emit this->sigPutLog(owner,level,text);
}

void Dbconnector_mysql::slotWrkFinish(const QString &sesstioID, QStringList data){

}

void Dbconnector_mysql::slotWrkError(const QString &sessionID, const QString &errtext){

}

Q_EXPORT_PLUGIN2(iDatabase,Dbconnector_mysql)
